<?php

namespace app\admin\controller;

use app\common\controller\Backend;

use think\Controller;
use think\Request;
use think\Config;
use think\Db;
use think\Log;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Repay extends Backend
{
    
    /**
     * BorrowRepay模型对象
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('BorrowRepay');

    }

    public function index()
    {
        //设置过滤方法
        //$this->request->filter(['strip_tags', 'htmlspecialchars']);

        $this->relationSearch = true;

        $this->searchFields = "borrow.borrowId";

        if ($this->request->isAjax())
        {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model->with("borrow,user")
                ->where($where)->where('borrow_repay.status',0)->group('borrow_repay.borrowId')
                ->order($sort, $order)
                ->count();

            $list = $this->model->with("borrow,user")
                ->where($where)->where('borrow_repay.status',0)->group('borrow_repay.borrowId')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach($list as $key => $val){
                $list[$key]['qishu'] = $val['period'].'/'.$val['totalPeriod'];
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    public function  repay(){

        $id = input('param.id');


        $repay = Db::name('borrow_repay')->where("repayId",$id)->find();
        ///api/manager/publishBorrow?borrowId=3&userId=2

        $url = Config::get('api_url');

        $data['borrowId'] = $repay['borrowId'];
        $data['period'] = $repay['period'];
        $data['userId'] = $this->auth->id;

        Log::record('还款post:'.json_encode($data));
        $result = postURL($url.'/api/manager/repayBorrow',$data);
        Log::record('还款返回:'.$result);

        $result = json_decode($result,true);


        if($result['code'] == 0){
            $this->code = 1;
        }else{
            $this->code =-1;
            $this->msg = $result['msg'];
        }

//        $this->code = 1;
        return;
    }


}
